#ifndef XX_COMMON_TCPSERVER_HH
#define XX_COMMON_TCPSERVER_HH
#include "httpSession.h"
#include "osip_mt.h"
#include "osip_net.h"
#include "osip_queue.h"
#include <JSONParse.h>
#include "common.h"
#include "log4z.h"
#include "Epoll.h"

#define max_connection 10000
#define readTCPBufLen 4096

template <typename T>
class TCPServer : public osip_thread
{
public:
	TCPServer() {
		m_server_fd = -1;
	}
	~TCPServer() {
		StopServer();
	}

	virtual int  StopServer() {
		osip_thread::Join();
		RemoveSession();
		fdClose(m_server_fd);
		return XX_ERR_ERROR;
	}

	virtual void  RemoveSession() {}

	virtual int  StartServer(socket_t Port) {
		// 初始化用于监听的套接字
		printf("Init listen...\n");
		m_server_fd = 0;
		m_server_fd = initListenFd(Port);
		if (m_server_fd == -1)
		{
			LOGFMTI("listen error");
			return -1;
		}

		return osip_thread::Start();
	}

	virtual void Run() {
#ifndef WIN32
		prctl(PR_SET_NAME, "TCPServer");
#endif

		socket_t fdClient = 0;
		Epoll epoll_http_server;
		if (epoll_http_server.addfd(m_server_fd)) {
			return;
		}

		//printf("||||||||||||||    while  begin  ||||||||||||||\n");
		while (!m_bThreadEnd) {
			int nReady = epoll_http_server.wait();
			for (int index = 0; index < nReady; ++index) {
				int client_fd = epoll_http_server.getEventOccurfd(index);
				uint32_t events = epoll_http_server.getEvents(index);
				if (client_fd == m_server_fd) {
					HandleAcceptEvent(epoll_http_server);
				}
				else if (events & EPOLLIN) {
					HandleReadEvent(client_fd);
				}
				else if (events & EPOLLOUT) {
					HandleWriteEvent(client_fd);
				}
				else if (events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
					//HandleErrorEvent(client_fd);
				}
			}
		}
	}

private:
	socket_t m_server_fd;

	void HandleAcceptEvent(Epoll& epoll) {
		struct sockaddr_in fdaddr;
		socklen_t fdlen = sizeof(fdaddr);
		socket_t fdClient = accept(m_server_fd, (struct sockaddr*)&fdaddr, &fdlen);
		if (fdClient > 0) {
			tcp_sockopt(fdClient);
			if (ThreadPoolWork::instance()->size() >= max_connection) {
				LOGFMTW("超过最大连接数:%d", ThreadPoolWork::instance()->size());
				fdClose(fdClient);
				return;
			}
			T* Session = new T();
			if (Session) {
				Session->StartServer(fdClient);
				ThreadPoolWork::instance()->addTask(Session);
			}
			else {
				LOGFMTW("new Session error");
				fdClose(fdClient);
			}
			LOGFMTI("IP:[%s:%d]", inet_ntoa(fdaddr.sin_addr), ntohs(fdaddr.sin_port));
		}
	}

	void HandleReadEvent(socket_t client_fd) {
		// Handle read event for the client_fd, e.g., read data from client
	}

	void HandleWriteEvent(socket_t client_fd) {
		// Handle write event for the client_fd, e.g., send data to client
	}
};

#endif
